package com.dts.yjnb.service.service.impl;

import com.dts.common.exception.ServiceException;
import com.dts.yjnb.service.domain.Market;
import com.dts.yjnb.service.domain.Product;
import com.dts.yjnb.service.mapper.MarketMapper;
import com.dts.yjnb.service.mapper.ProductMapper;
import com.dts.yjnb.service.service.ReportService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.List;
@Service
public class ReportServiceImpl implements ReportService {
    
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private MarketMapper marketMapper;
    
    @Override
    public void exportBusinessDate(HttpServletResponse response) throws IOException {
        //1.查询数据库，获取营业数据

        // 开始分页
        Product product = new Product();
        PageHelper.startPage(1, 10);
        Page<Product> page = productMapper.pageQuery(product);

        long total = page.getTotal();
        List<Product> records = page.getResult();

        //2.通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/product.xlsx");

        XSSFWorkbook excel = new XSSFWorkbook(in);

        //第一张xlsx数据页
        XSSFSheet sheet = excel.getSheetAt(0);

        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Integer count = 1;
        for (Product record : records) {
            //第count行
            XSSFRow row = sheet.createRow(count);

            Long categoryid = record.getCategoryId();

            row.createCell(0).setCellValue(record.getName());
            row.createCell(2).setCellValue(
                    categoryid == 1 ? "蔬菜" :
                    categoryid == 2 ? "水果" :
                    categoryid == 3 ? "肉禽" :
                    categoryid == 4 ? "水产" :
                    categoryid == 5 ? "米面粮油" :
                    categoryid == 6 ? "调味干货" :
                    categoryid == 7 ? "乳制品" :
                    categoryid == 8 ? "饮料" :
                    categoryid == 9 ? "花卉药材" : "其它");
            row.createCell(3).setCellValue(record.getPrice().doubleValue());
            row.createCell(4).setCellValue(record.getCreateTime() != null ? dateFormat.format(record.getCreateTime()) : "");
            row.createCell(5).setCellValue(record.getIsRecommend() == 1 ? "是" : "否" );
            row.createCell(6).setCellValue(record.getStatus() == 1 ? "上架" : "下架");

            count++;
        }

        //3.通过输出流将Rxcel文件下载到客服端浏览器
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        //关闭资源
        out.close();
        excel.close();
    }
    /**
     * 导出农贸市场数据到Excel
     *
     * @param response HTTP响应
     * @throws IOException IO异常
     */
    @Override
    public void exportMarketData(HttpServletResponse response) throws IOException {
        // 1. 查询数据库，获取所有市场数据
        List<Market> records = marketMapper.selectAll();

        // 2. 通过POI将数据写入到Excel文件中
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("templates/market.xlsx");

        if (in == null) {
            throw new ServiceException("导出模板文件不存在");
        }

        XSSFWorkbook excel = new XSSFWorkbook(in);

        // 获取第一张工作表
        XSSFSheet sheet = excel.getSheetAt(0);

        // 创建日期格式化对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        // 从第2行开始写入数据（第1行是标题）
        int rowNum = 1;
        for (Market record : records) {
            XSSFRow row = sheet.createRow(rowNum);

            // 市场编号
            row.createCell(0).setCellValue(record.getMarketId());
            // 市场名称
            row.createCell(1).setCellValue(record.getMarketName());
            // 所在地区
            row.createCell(2).setCellValue(record.getRegion());
            // 创建时间
            row.createCell(3).setCellValue(
                    record.getCreateTime() != null ? dateFormat.format(record.getCreateTime()) : ""
            );
            // 修改时间
            row.createCell(4).setCellValue(
                    record.getModifyTime() != null ? dateFormat.format(record.getModifyTime()) : ""
            );

            rowNum++;
        }

        // 3. 设置响应头，让浏览器下载文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=market_" + System.currentTimeMillis() + ".xlsx");

        // 4. 通过输出流将Excel文件下载到客户端浏览器
        ServletOutputStream out = response.getOutputStream();
        excel.write(out);

        // 关闭资源
        out.flush();
        out.close();
        excel.close();
        in.close();
    }

}
